package main

import (
	"os"
	"runtime"

	//	l4g "code.google.com/p/log4go"
	"github.com/op/go-logging"
	"github.com/valyala/fasthttp"
	"gopkg.in/alecthomas/kingpin.v2"
)

func init() {
	var logBackend = logging.NewLogBackend(os.Stdout, "", 0)
	format := logging.MustStringFormatter(
		`%{color}%{time:2006-01-02 15:04:05.000} %{shortfunc} %{level:.4s} %{id:03x}%{color:reset} %{message}`)
	logging.SetFormatter(format)
	logging.SetBackend(logBackend)
	runtime.GOMAXPROCS(runtime.NumCPU()) //充分利用cpu
}

var LOG = logging.MustGetLogger("router")

func main() {
	logging.SetLevel(logging.INFO, "router")
	port := kingpin.Flag("port", "port").Default("8085").String()
	//monitorPort := kingpin.Flag("monitor_port", "monitor_port").Default("8086").String() //prome端口
	monitorPort := kingpin.Flag("monitor_port", "monitor_port").String() //prome端口
	redisConfFile := kingpin.Flag("redis_conf", "redis_conf").String()
	servermapFile := kingpin.Flag("server_map", "server_map").String()
	mode := kingpin.Flag("mode", "mode").String()            //切换接口
	logFile := kingpin.Flag("log_file", "log_file").String() //存放日志文件

	kingpin.Parse() //需要先解析得到参数后才使用

	if logFile != nil {
		f, err := os.OpenFile(*logFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
		if err != nil {
			os.Exit(2)
		}

		var logBackend = logging.NewLogBackend(f, "", 0)
		logging.SetBackend(logBackend)
		LOG = logging.MustGetLogger("router")

	}

	LOG.Infof("loaded from  %s %s \n", *servermapFile, *redisConfFile)

	//	gw, err := NewDocServiceGateWay(*servermapFile, *redisConfFile)
	//	if err != nil {
	//		LOG.Errorf("init gateway error %v", err)
	//		os.Exit(2)
	//	}

	var gw GateWay
	var err error
	switch *mode {
	case "docservice":
		gw, err = NewDocServiceGateWay(*servermapFile, *redisConfFile)
		if err != nil {
			LOG.Errorf("init docservice gateway error %v", err) //红色的显示
			os.Exit(2)
		}
	case "repeater":
		gw, err = NewRepeaterGateWay(*servermapFile) //因为要返回给gw，所以
		if err != nil {
			LOG.Errorf("init repeater gateway error %v", err)
			os.Exit(2)
		}
	default:
		LOG.Errorf("unsupported mode: %s", *mode)
		os.Exit(2)
	}

	counter := NewCounter() //初始化
	rt := Router{
		timeout: 15,
		gateway: gw,
		counter: counter,
	}
	if err = rt.init(); err != nil { //开始启动一个http.client
		//为了控制HTTP客户端的headers、重定向方案和其它设定，需要创建一个Client：
		LOG.Errorf("init router error: %v", err)
		os.Exit(2)
	}

	if monitorPort != nil { //8086 listen是阻塞的，写在一个go func()中 另起一个goroutine
		go func() {
			LOG.Infof("start prome server on port: %s", *monitorPort) //自动起个端口监听
			err := fasthttp.ListenAndServe(":"+*monitorPort, counter.Handler)
			if err != nil { //添加判断
				LOG.Error("prome server err:%v", err)
			}
		}()
	}

	server := &fasthttp.Server{ //对服务端行为的控制
		Handler:           rt.Handler, //大Handler: Handler for processing incoming requests.
		ReadBufferSize:    1024 * 4,
		WriteBufferSize:   1024 * 4,
		ReduceMemoryUsage: true,
		DisableKeepalive:  true,
	}
	LOG.Infof("starting on port %s", *port)
	err = server.ListenAndServe(":" + *port)
	if err != nil {
		LOG.Errorf("server error: %v", err)
		os.Exit(2)
	}

}
